<?php

namespace app\admin\controller\user;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\user\Scorelog;
use app\admin\model\shopro\user\Silverlog;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\WalletLog;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\GoldenLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\shopro\CarQueue;
use app\common\model\shopro\ShoproPerformanceModel;
use app\common\model\shopro\UserReleaseModel;
use app\common\model\Userchildren;
use fast\Random;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-circle-o
 */
class Usertwo extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * Usertwo模型对象
     * @var \app\admin\model\user\Usertwo
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Usertwo;
        $this->view->assign("isExperienceStoreList", $this->model->getIsExperienceStoreList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payList", $this->model->getPayList());
        $this->view->assign("paRateList", $this->model->paRateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['parentuser'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['id','username','invite_code','email','mobile','avatar','level','money','score','firepower','golden','silver','gold','createtime','status','total_consume','pa_rate','team_buy_money','is_manager','is_withdraw','is_firepower','is_frozen','is_lock','is_partner','principal','is_old']);

                $row->visible(['parentuser']);
                $row->getRelation('parentuser')->visible(['nickname','mobile']);
            }
            $data  = $list->toArray();
            foreach ($data['data'] as $k=>&$v){
                $parent_user_data = UserModel::where(['parent_user_id' => $v['id']])->field('id,team_buy_money + total_consume as all_money')->order('all_money desc')->select();
                $v['xiaoquyeji'] = 0;
                $v['daquyeji']   = 0;
//                $v['team_buy_money'] = round($v['team_buy_money']*480,2);
                if ($parent_user_data) {
                    $xiaoquyeji = 0;
                    foreach ($parent_user_data as $kk => $vv) {
                        if ($kk > 0) {
                            $xiaoquyeji += $vv['all_money'];
                        }else{
                            $v['daquyeji'] =$vv['all_money'];
                        }
                    }
                    $v['xiaoquyeji'] = $xiaoquyeji;
                }
            }
            $result = array("total" => $list->total(), "rows" => $data['data']);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function recharge($params)
    {
        Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [],
                $params['memo']);
        });
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $auth                     = new Auth();
            $extend['username']       = $params['username'];
            $extend['parent_user_id'] = $params['parent_user_id'];
//            $extend['gold']           = $params['gold'];
            $extend['golden']         = $params['golden']??0;
            $extend['silver']         = $params['silver']??0;
            $extend['score']          = $params['score']??0;
            $extend['invite_code'] = Random::alnum(8);
            $result =  $auth->register($params['nickname'], $params['password'], $params['email'], $params['mobile'], $extend);
            if(!$result){
                $this->error($auth->getError());
            }
            $arr['memo']   = '管理员操作';
            $arr['amount'] = $params['money'];
            $arr['id']     = $auth->getUserinfo()['id'];
            if($params['money'] != 0){
                $arr['type'] = 'money';
                $this->recharge($arr);
            }
            if($params['score'] != 0){
                $arr['id'] = $auth->getUserinfo()['id'];
                $arr['type'] = 'score';
                $this->recharge($arr);
            }
            if($params['golden'] != 0){
                $arr['type'] = 'golden';
                $this->recharge($arr);
            }
//            if($params['gold'] != 0){
//                $arr['type'] = 'gold';
//                $this->recharge($arr);
//            }
            if($params['silver'] != 0){
                $arr['type'] = 'silver';
                $this->recharge($arr);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 充值
     *
     * @return string
     * @throws \think\Exception
     */
    public function chongzhi($id)
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!in_array($params['type'], ['money', 'score', 'golden', 'gold', 'principal','silver','firepower','score_gift'])) {
            $this->error('参数错误');
        }
        $row = $this->model->where(['id'=>$id])->find();
        if($params['type'] == 'principal' && $row->is_old == 0){
            $this->error('新用户不能增加本金');
        }
        if($params['type'] == 'score_gift'){
            if($row){
                $row->setInc('score_gift',$params['amount']);
            }
        }else{
            $params['id'] = $id;
            $this->recharge($params);
        }
        $this->success();
    }

    /**
     * @menu 禁用团队登录
     * @Author:男人的坏
     * @Date:2024-04-15 20:04
     */

    public function jinyong($ids){
        $status  = input('status');
        $model = new \app\admin\model\Children;
        $children = $model->where(['member_id'=>$ids])->column('children_id');
        if(!$children){
            $this->error('当前用户无团队');
        }
        $is_withdraw = input('is_withdraw');
        $is_firepower = input('is_firepower');
        if(isset($is_withdraw)){
            $up['is_withdraw'] = $is_withdraw;
        }
        if(isset($is_firepower)){
            $up['is_firepower'] = $is_firepower;
        }
        if($status){
            $up['status'] = $status;
        }
        $this->model->whereIn('id', $children)->update($up);
        $this->success('操作成功');
    }


    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
//        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
//        if (empty($values)) {
//            $this->error(__('You have no permission'));
//        }
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            $this->model->where($this->dataLimitField, 'in', $adminIds);
//        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                WalletLog::where(['user_id'=>$item->id])->delete();
                MoneyLog::where(['user_id'=>$item->id])->delete();
                Scorelog::where(['user_id'=>$item->id])->delete();
                GoldenLog::where(['user_id'=>$item->id])->delete();
                Silverlog::where(['user_id'=>$item->id])->delete();
                GoldLog::where(['user_id'=>$item->id])->delete();
                Userchildren::where(['children_id'=>$item->id])->delete();
                Order::where(['user_id'=>$item->id])->delete();
                $this->model->where(['parent_user_id'=>$item->id])->update(['parent_user_id'=>$item->parent_user_id]);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }



    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($params['parent_user_id'] != $row['parent_user_id']){
                Userchildren::where(['children_id'=>$row['id']])->delete();
                $row['parent_user_id'] = $params['parent_user_id'];
                \think\Hook::listen('user_register', $row);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
